package gui;

import processing.core.PApplet;

public class PColor extends Axes {
	private double[][] data;
	private float dx, dy;
	private int nx, ny;
	private double min, max, mean;
	private boolean dataRangeIsSet;
	private PColor colorbar;
	
	public PColor(PApplet parentApplet, float[] r, 
			double[] xdata, double[] ydata, double[][] data, 
			Object... args) {
		super(parentApplet, r, xdata, ydata, args);
		assert ydata.length == data.length;
		assert xdata.length == data[0].length;
		nx = data[0].length;
		ny = data.length;	
		dx = r[2]/nx;
		dy = r[3]/ny;

		dataRangeIsSet = false;
		updateData(data);		
	}

	public void setDataRange(double min, double max) {
		this.min = min;
		this.max = max;
		mean = (max+min)/2.;
		dataRangeIsSet = true;
	}
	
	public void setDataRange(float min, float max) {
		setDataRange((double)min, (double)max);
		dataRangeIsSet = true;
	}
	
	public void colorbar() {
		float[] r = {x0 + width + (float)30., (float)y0, (float)20., height};
		double[] xdata = new double[1];
		double[] ydata = new double[101];
		double[][] data = new double[101][1]; 

		xdata[0] = 0.;
		for (int i=0; i<101; i++) {
			ydata[i] = min*(1.-(double)i/100.) + max*(double)i/100.;
			data[i][0] = ydata[i];
		}

		colorbar = new PColor(pa, r, xdata, ydata, data);
	}
	
	private void updateColorbar() {
		colorbar();
	}
	
	private void findMinMaxMean() {
		min = data[0][0];
		max = data[0][0];
		mean = 0.;
        for (int j=0; j < ny; j++) {      
	        for (int i=0; i < nx; i++) {
	        	double temp = data[j][i];
	        	mean = mean + temp;
	        	if (temp < min) {
	        		min = temp;
	        	}
	        	if (temp > max){
	        	    max = temp;	
	        	}
	        }
        }
		mean = mean/(double)nx/(double)ny;     
	}
	
	public void updateData(double[][] data) {
        this.data = data;
        if (!dataRangeIsSet) findMinMaxMean();
        if (colorbar != null) updateColorbar();
	}
	
	public void draw() {
        pa.noStroke();
		  
        for (int j=0; j < ny; j++) {      
	        for (int i=0; i < nx; i++) {
	            double temp;
	            int colour;

	            temp = (data[j][i] - mean)/(max-min)*510.;
	            colour = (int) temp;
	            if (colour > 0) {
	                pa.fill(255, 255-colour, 255-colour);
	            }
	            else{
	    	        pa.fill(255+colour, 255+colour, 255);
	            }
	            
	            float x = x0 + (float)(i)*dx;
	            float y = y0 + (float)(j)*dy;

		        pa.rect(x, y, dx, dy);
            }
        }  
	    super.draw();
	    if (colorbar != null) colorbar.draw();
	}
}
